hosts: all
  remote_user: root
  roles:
  - roles

  tasks:
    - name: add localhost4
      local_action: shell echo "127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4" > {{AnsibleDir}}/roles/templates/hosts.j2
      run_once: true
    - name: add localhost6
      local_action: shell echo "::1         localhost localhost.localdomain localhost6 localhost6.localdomain6" >> {{AnsibleDir}}/roles/templates/hosts.j2
      run_once: true
    - set_fact: ipaddress={{hostvars[inventory_hostname].ansible_default_ipv4.address}}  #获取各个节点IP地址并设置成变量
    - set_fact: hostname={{hostvars[inventory_hostname].ansible_facts.hostname}}  #获取各个节点主机名并设置成变量
    - name: add host record #添加所有ipaddress hostname追加到本机
      local_action: shell echo {{ipaddress}} {{hostname}} >> {{AnsibleDir}}/roles/templates/hosts.j2
    - name: copy hosts.j2 to all #将新的hosts.j2分发到各个节点上
      template: src={{AnsibleDir}}/roles/templates/hosts.j2 dest=/tmp/hosts
————————————————
版权声明：本文为CSDN博主「雷禄辉」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
原文链接：https://blog.csdn.net/a544258023/java/article/details/86061958